package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BusinessException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService service;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;

    //新增套餐
    @PostMapping
    @CacheEvict(value = "setmeal",key = "#setmealDto.categoryId")
    public R saveSetmeal(@RequestBody SetmealDto setmealDto) {

        //保存套餐数据到 setmeal（套餐）表中
        service.save(setmealDto);
        //保存套餐下的菜品到setmeal_dish（套餐菜品）表中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);

        return R.success("新增套餐成功");
    }

    @GetMapping("/page")
    public R pageQuery(int page, int pageSize, String name) {

        //进行分页查询
        Page<Setmeal> Page = new Page<>(page, pageSize);
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Setmeal::getName, name);
        wrapper.orderByDesc(Setmeal::getUpdateTime);
        service.page(Page, wrapper);
        long total = Page.getTotal();
        List<Setmeal> setmeals = Page.getRecords();
        Map map = new HashMap();
        map.put("total", (int) total);
     /*   List<SetmealDto> setmealDtos = new ArrayList<>();
        for (Setmeal setmeal : setmeals) {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal,setmealDto);
            Long categoryId = setmeal.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            if(byId!=null){
                setmealDto.setCategoryName(byId.getName());
            }
            setmealDtos.add(setmealDto);
        }*/
        List<SetmealDto> setmealDtos = setmeals.stream().map((setmeal) -> {
             SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal, setmealDto);
            Long categoryId = setmeal.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            if (byId != null) {
                setmealDto.setCategoryName(byId.getName());
            }
            return setmealDto;
        }).collect(Collectors.toList());

        map.put("records", setmealDtos);

        return R.success(map);
    }

    @DeleteMapping
    @CacheEvict(value = "setmeal",allEntries = true)
    public R deleteSetmeal(@RequestParam List<Long> ids) {
        //select count(*) from setmeal where id in (1,2,3) and status = 1
        //查询套餐状态，确定是否可用删除
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId, ids);
        wrapper.eq(Setmeal::getStatus, 1);
        int count = service.count(wrapper);
        if (count > 0) {
            //不能删除，抛出一个业务异常
            throw new BusinessException("套餐正在售卖中，不能删除");
        }
        //如果可以删除，先删除套餐表中的数据---setmeal
        service.removeByIds(ids);
        //delete from setmeal_dish where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(SetmealDish::getSetmealId, ids);
        //删除关系表中的数据----setmeal_dish
        setmealDishService.remove(wrapper1);
        return R.success("套餐数据删除成功");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmeal",allEntries = true)
    public R updateSetmealStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        LambdaUpdateWrapper<Setmeal> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Setmeal::getStatus, status);
        wrapper.in(Setmeal::getId, ids);
        service.update(wrapper);
        return R.success(null);
    }

    @GetMapping("/{id}")
    public R getByIdQuery(@PathVariable Long id) {
        //查询套餐的基础信息，从 setmeal 表中查询
        Setmeal setmeal = service.getById(id);
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        //查询套餐中包含的菜品信息，从 setmeal_dish 中查询
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishService.list(wrapper);
        setmealDto.setSetmealDishes(setmealDishes);
        return R.success(setmealDto);
    }

    @PutMapping
    @CacheEvict(value = "setmeal",allEntries = true)
    public R updateSetmeal(@RequestBody SetmealDto setmealDto) {
        System.out.println(setmealDto);
        //更新setmeal套餐表基本信息
        service.updateById(setmealDto);
        //清理当前套餐对应的菜品数据
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(wrapper);
        //添加当前套餐提交过来的菜品数据
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
        return R.success(null);
    }
    //查询分类下的所有套餐
    @Cacheable(value = "setmeal",key = "#categoryId")  // 存缓存
    @GetMapping("/list")
        public R list(Long categoryId, Integer status) {
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.eq(Setmeal::getCategoryId,categoryId);
        qw.eq(Setmeal::getStatus,status);
        List<Setmeal> list = service.list(qw);
        return R.success(list);
    }

}
